package com.ruge.act;

import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.UserTask;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricVariableInstance;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.task.IdentityLink;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ActivitiHistoryQuery {

    @Autowired
    private HistoryService historyService;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    /**
     * 获取流程实例的所有审批节点信息
     */
    public List<Map<String, Object>> getProcessApprovalInfo(String processInstanceId) {
        List<Map<String, Object>> result = new ArrayList<>();

        // 查询历史任务实例
        List<HistoricTaskInstance> historicTasks = historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(processInstanceId)
                .orderByHistoricTaskInstanceStartTime().asc()
                .list();

        for (HistoricTaskInstance task : historicTasks) {
            Map<String, Object> taskInfo = new HashMap<>();
            taskInfo.put("任务ID", task.getId());
            taskInfo.put("任务名称", task.getName());
            taskInfo.put("任务定义Key", task.getTaskDefinitionKey());
            taskInfo.put("开始时间", task.getStartTime());
            taskInfo.put("结束时间", task.getEndTime());
            taskInfo.put("持续时间", task.getDurationInMillis());
            taskInfo.put("审批人", task.getAssignee());

            // 获取任务的候选组（角色）
            List<IdentityLink> identityLinks = taskService.getIdentityLinksForTask(task.getId());
            List<String> candidateGroups = new ArrayList<>();
            for (IdentityLink link : identityLinks) {
                if ("candidate".equals(link.getType()) && link.getGroupId() != null) {
                    candidateGroups.add(link.getGroupId());
                }
            }
            taskInfo.put("候选角色", candidateGroups);

            // 获取任务变量（修正方法调用）
            Map<String, Object> taskVariables = historyService
                    .createHistoricVariableInstanceQuery()
                    .taskId(task.getId())
                    .list()
                    .stream()
                    .collect(Collectors.toMap(
                            HistoricVariableInstance::getVariableName,
                            HistoricVariableInstance::getValue
                    ));
            taskInfo.put("任务变量", taskVariables);

            result.add(taskInfo);
        }

        return result;
    }

    /**
     * 获取流程定义中的所有用户任务节点及配置的候选组
     */
    public Map<String, List<String>> getProcessDefinitionTaskRoles(String processDefinitionId) {
        Map<String, List<String>> result = new HashMap<>();

        // 获取流程定义
        ProcessDefinition processDefinition = repositoryService.getProcessDefinition(processDefinitionId);
        
        // 修正：通过 BpmnModel 获取流程元素
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
        Collection<FlowElement> flowElements = bpmnModel.getMainProcess().getFlowElements();

        // 遍历所有用户任务节点
        for (FlowElement flowElement : flowElements) {
            if (flowElement instanceof UserTask) {
                UserTask userTask = (UserTask) flowElement;
                result.put(userTask.getName(), userTask.getCandidateGroups());
            }
        }

        return result;
    }
}    